package es.puravida.watchuoc.service;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import es.puravida.watchuoc.R;
import es.puravida.watchuoc.WatchUOCApplication;
import es.puravida.watchuoc.R.drawable;
import es.puravida.watchuoc.R.id;
import es.puravida.watchuoc.client.SituacionActivity;
import es.puravida.watchuoc.client.WatchUOCActivity;
import es.puravida.watchuoc.util.MyHTTPClient;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.EditText;

public class WatchUOCService extends Service {

	private static final String TAG = WatchUOCService.class.getName();

	private NotificationManager notificationMgr;

	private String username;
	private String pwd;
	private int mensajes;

	private Timer timer = new Timer();
	private static final long UPDATE_INTERVAL = 1000 * 60 * 60; // 1h

	@Override
	public void onCreate() {
		Log.d(TAG, "onCreate");
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		if (timer != null)
			timer.cancel();
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		handleCommand(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handleCommand(intent);
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		return START_STICKY;
	}

	protected void handleCommand(Intent intent) {
		username = intent.getStringExtra("es.puravida.watchuoc.username");
		pwd = intent.getStringExtra("es.puravida.watchuoc.password");
		mensajes = intent.getIntExtra("es.puravida.watchuoc.minmensajes", 999);
		Log.d(TAG, username);
		Log.d(TAG, pwd);
		notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				doProcess();
			}
		}, 0, UPDATE_INTERVAL);
	}

	protected void doProcess() {
		Map<String, Integer> aulas = connectAndParse();
		int hay = 0;
		for (Integer value : aulas.values()) {
			hay += value.intValue();
		}
		if (mensajes <= hay) {
			Bundle bundle = new Bundle();
			String[] str = aulas.keySet().toArray(new String[] {});
			bundle.putStringArray("es.puravida.watchuoc.aulas", str);
			for (String key : aulas.keySet()) {
				bundle.putInt("es.puravida.watchuoc.aulas." + key,
						aulas.get(key));
			}
			displayNotificationMessage("Hay " + hay + " mensajes en los foros",
					SituacionActivity.class, bundle);
		}
	}

	private void displayNotificationMessage(String message, Class intentClazz) {
		displayNotificationMessage(message, intentClazz, null);
	}

	private void displayNotificationMessage(String message, Class intentClazz,
			Bundle bundle) {

		Notification notification = new Notification(R.drawable.icon, message,
				System.currentTimeMillis());
		//#issue 7
		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.defaults |= Notification.DEFAULT_VIBRATE;

		Intent intent = new Intent(this, intentClazz);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				intent, 0);

		notification.setLatestEventInfo(this, "WatchUOC", message,
				contentIntent);

		notificationMgr.notify(R.id.app_notification_id, notification);

		// tras la notificacion terminar el servicio y esperar que nos vuelvan a
		// lanzar
		try{
		if (timer != null)
			timer.cancel();
		}catch(Exception e){
			Log.e(TAG,e.getMessage(),e);
		}
		//this.stopSelf();
	}

	protected boolean checkInternet() {
		android.net.ConnectivityManager cm = (android.net.ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		android.net.NetworkInfo comprueboInternet = cm.getActiveNetworkInfo();
		if (comprueboInternet != null
				&& comprueboInternet.isConnectedOrConnecting()) {
			return true;
		} else {
			Log.d(TAG, "No hay red");
			return false;
		}
	}

	public Map<String, Integer> connectAndParse() {
		Map<String, Integer> ret = new HashMap<String, Integer>();
		try {
			if (checkInternet()) {
				WatchUOCApplication app = (WatchUOCApplication) getApplication();
				MyHTTPClient client = app.getHttpClient();
				Log.d(WatchUOCService.this.getClass().getName(), "do login");
				if (doLoginUOC(client, username, pwd)) {
					JSONArray aulas = doGetHomePage(client);
					for (int i = 0; i < aulas.length(); i++) {
						JSONObject aula = aulas.getJSONObject(i);
						if (aula.has("title") && aula.has("resources")) {
							JSONArray resources = aula
									.getJSONArray("resources");
							for (int r = 0; r < resources.length(); r++) {
								JSONObject resource = resources
										.getJSONObject(r);
								if (resource.has("numMesPend")) {
									//#issue 3
									Integer anterior = ret.get(aula.getString("title"));
									if(anterior==null){
										anterior=new Integer(0);
									}
									anterior += resource.getInt("numMesPend");		
									ret.put(aula.getString("title"),anterior);
									//#issue 3									
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			Log.d(WatchUOCService.this.getClass().getName(), e.getMessage(), e);
		}
		return ret;
	}

	private boolean doLoginUOC(MyHTTPClient client, String sLogin, String sPass) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		params.add(new BasicNameValuePair("l", sLogin));
		params.add(new BasicNameValuePair("p", sPass));
		params.add(new BasicNameValuePair("appid", "WUOC"));
		params.add(new BasicNameValuePair("nil", "XXXXXX"));
		params.add(new BasicNameValuePair("lb", "a"));
		params.add(new BasicNameValuePair("url", "http://cv.uoc.edu"));
		params.add(new BasicNameValuePair("x", "13"));
		params.add(new BasicNameValuePair("y", "2"));

		String resp = client.doPost("http://cv.uoc.edu/cgi-bin/uoc", params);
		if (resp == null) {
			displayNotificationMessage("Error en login", WatchUOCActivity.class);
			return false;
		}

		int iErr = resp.indexOf("var error = '");
		if (iErr > 0) {
			int iFin = resp.indexOf("';", iErr);

			if (resp.substring(iErr + 13, iFin).startsWith(
					"El nom d´usuari o la contrasenya són incorrectes")) {
				displayNotificationMessage("Error en login",
						WatchUOCActivity.class);
			} else {
				displayNotificationMessage(resp.substring(iErr + 13, iFin),
						WatchUOCActivity.class);
			}
			return false;
		}

		if (client.getCookieStore().getCookies().isEmpty()) {
			displayNotificationMessage("No hay cookies", WatchUOCActivity.class);
			return false;
		}

		// Obtenemos la sesión...
		String sSession = null;
		int iSs = resp.indexOf("?s=");
		if (iSs <= 0) {
			displayNotificationMessage("No hay session", WatchUOCActivity.class);
			return false;
		}

		int iSf = resp.indexOf("\";", iSs);
		sSession = resp.substring(iSs + 3, iSf);
		client.setSessionUOC(sSession);

		return true;
	}

	private JSONArray doGetHomePage(MyHTTPClient client) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("s", client.getSessionUOC()));
		params.add(new BasicNameValuePair("newStartingPage", "0"));
		params.add(new BasicNameValuePair("language", "b"));
		String page = client.doGet("http://cv.uoc.edu/UOC2000/b/cgi-bin/hola",
				params);
		if (page == null) {
			displayNotificationMessage("Error accediendo a UOC",
					WatchUOCActivity.class);
			return null;
		}

		int index = page.indexOf("aulas = ");
		if (index != -1) {
			StringBuffer buffer = new StringBuffer();
			buffer.append(page.substring(index + 8));
			int last = buffer.indexOf(";");
			buffer.delete(last, buffer.length());
			Log.d(TAG, buffer.toString());
			try {
				JSONArray obj = (JSONArray) new JSONTokener(buffer.toString())
						.nextValue();
				Log.d(TAG, obj.toString());
				return obj;
			} catch (Exception e) {
				Log.e(TAG, "getHomePage", e);
				return null;
			}
		}
		return null;
	}
}
